package com.smy.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
/**
 * 全局异常处理器
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalException {
    /**
     * 添加重复异常捕获
     * */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> alreadyExistsException(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error(message);
        if(message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            String msg = s[2].substring(1,s[2].length()-1) + " 已存在！";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException ex){
        String message = ex.getMessage();
        log.error(message);
        if (message.equals(""))return R.error("未知错误");
        return R.error(message);
    }
}
